import { combineReducers } from "redux";
import {handleActions} from "redux-actions";

export default async (options)=>{
    const {entry, globalAction} = options
    const business = await require(entry);
    const reduders = {};
    const promises = [] as any[];
    const result = Object.keys(business).map((r, i) => {
        return new Promise(res => {
            promises.push(res);
        });
    });

    Object.keys(globalAction).forEach(async (name, i) => {
        const localReducer = {};
        const scope = globalAction[name];
        Object.keys(scope.actions).forEach(t=>{
            localReducer[`global.${name}.${t}`] = scope.actions[t].reducer;
        })
        reduders[name] = handleActions(localReducer, scope.initialState || "");
    });

    Object.keys(business).forEach(async (b, i) => {
        const [mAction, mProps] = await Promise.all([
            require(`${entry}/${b}/action`),
            require(`${entry}/${b}/props`)
        ]);
        const localReducer = {};
        Object.keys(mAction.default).forEach((r: any) => {
            // 按照 `模块名 + 点 + action名进行约定性命名`，此处是对reducer对数据回流进行切片操作
            localReducer[`${b}.${r}`] = mAction.default[r].reducer;
        });
        reduders[b] = handleActions(localReducer, mProps.default.initialState || "");
        promises[i]();
    });

    return Promise.all(result).then(() => combineReducers(reduders));
}
